package com.example.com.test.player;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.MediaController;

import com.example.com.test.application.App;
import com.example.com.test.impl.AudioImpl;
import com.example.com.test.model.AudioModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者： ch
 * 时间： 2018/9/6 0006-下午 4:41
 * 描述：
 * 来源：
 */

public class MyMediaPlayer implements MediaController.MediaPlayerControl {

    public static MyMediaPlayer myMediaPlayer;
    private MediaController controller;
    private MediaPlayer mediaPlayer;
    private MyController myController;
    private MyPlayFinishListener finishListener;
    private MyErrorListener errorListener;

    private List<AudioModel> audioModel;
    private int position = -1;

    public List<AudioModel> getAudioModel() {
        return audioModel;
    }

    public int getPosition() {
        return position;
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 0) {
                if (myController != null) {
                    float progress = getCurrentPosition() / (float) getDuration();
                    currentProgress = (int) (progress * 100);
                    myController.onProgress(currentProgress);
                }
                handler.sendEmptyMessageDelayed(0, 500);
            }

        }
    };

    private String currentPath;
    private boolean isPlay;
    public boolean isPause;
    public boolean isReplay;
    //是否已经准备好
    public boolean isPrepare;

    private int currentProgress;


    public static MyMediaPlayer getInstance() {
        if (myMediaPlayer == null) {
            myMediaPlayer = new MyMediaPlayer();
        }
        return myMediaPlayer;
    }

    public MyMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        controller = new MediaController(App.getContext());
        controller.setMediaPlayer(this);

        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {

                if (errorListener != null) {
                    errorListener.onError("what=" + what + ",extra=" + extra);
                }
                return true;
            }
        });


        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

                if (audioModel == null || audioModel.size() == 0 || position < 0) {
                    return;
                }
                if (position + 1 < audioModel.size()) {
                    position++;
                    play(audioModel, position);
                    //添加已读
                    AudioImpl.addAudio(audioModel.get(position).getId());

                    if (finishListener != null) {
                        finishListener.onfinish(audioModel.get(position).getId());
                    }
                } else {
                    //没有下一个
                    if (finishListener != null) {
                        finishListener.onfinish(null);
                    }
                }


            }
        });
    }

    /**
     * 开始播放
     *
     * @param audioModels
     * @param position
     */
    public void play(List<AudioModel> audioModels, int position) {
        if (audioModels == null || audioModels.size() == 0 || position < 0) {
            return;
        }

        this.audioModel = audioModels;
        this.position = position;

        if (isPlaying(audioModel.get(position).getUrl())) {
//            MyMediaPlayer.getInstance().pause();
        } else {
            start(audioModel.get(position).getUrl());
        }
    }

    /**
     * 开始播放
     *
     * @param
     * @param
     */
    public void play(AudioModel audioModel) {
        if (audioModel == null) {
            return;
        }

        List<AudioModel> models = new ArrayList<>();
        models.add(audioModel);
        this.audioModel = models;
        this.position = 0;

        if (isPlaying(audioModel.getUrl())) {
//            MyMediaPlayer.getInstance().pause();
        } else {
            start(audioModel.getUrl());
        }
    }

    /**
     * 下一首
     *
     * @return
     */
    public String next() {
        if (audioModel == null || audioModel.size() == 0 || position < 0) {
            return null;
        }
        //有下一个
        if (position + 1 < audioModel.size()) {
            position++;
            start(audioModel.get(position).getUrl());

            return audioModel.get(position).getId();
        }

        return null;

    }

    /**
     * 上一首
     *
     * @return
     */
    public String before() {
        if (audioModel == null || audioModel.size() == 0 || position < 0) {
            return null;
        }

        if (position - 1 >= 0) {
            position--;
            start(audioModel.get(position).getUrl());
            return audioModel.get(position).getId();
        }

        return null;
    }

    /**
     * 开始播放
     *
     * @param path
     */
    public void start(String path) {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            if (controller == null) {
                controller = new MediaController(App.getContext());
                controller.setMediaPlayer(this);
            }
        }

        if (TextUtils.isEmpty(path)) {
            return;
        }
        if (currentPath == null) {
            currentPath = path;
        } else {
            if (currentPath.equals(path)) {
                //暂停时  需要重新播放

                if (isPause) {
                    mediaPlayer.start();
                }

                return;
            } else {
                currentPath = path;
                isPrepare = false;
                mediaPlayer.reset();

                if (myController != null) {
                    myController.onProgress(0);
                }
            }
        }

        try {

            mediaPlayer.setDataSource(path);
            isPlay = true;
            // 通过异步的方式装载媒体资源
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    isPrepare = true;
                    // 装载完毕回调
                    mediaPlayer.start();
                    isPause = false;
                    handler.sendEmptyMessageDelayed(0, 500);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public void seekToPosition(int pos) {
        if (mediaPlayer == null) {
            return;
        }
        int time = mediaPlayer.getDuration() * pos / 100;
        //毫秒
        mediaPlayer.seekTo(time);
    }


    /**
     * 停止
     */
    public void stop() {
        if (mediaPlayer == null) {
            return;
        }
        if (handler != null) {
            handler.removeMessages(0);
        }
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        currentPath = null;
        isPlay = false;
        isPause = false;
    }

    /**
     * 播放状态
     *
     * @param path
     * @return
     */
    public boolean isPlaying(String path) {
        if (TextUtils.isEmpty(path) || TextUtils.isEmpty(currentPath)) {
            return false;
        }

        if (!currentPath.equals(path)) {
            return false;
        }

        if (isPlay) {
            return true;
        }
        return mediaPlayer.isPlaying();
    }

    @Override
    public void start() {

    }

    /**
     * 暂停
     */
    public void pause() {
        pause(false);
    }

    /**
     * 暂停
     */
    public void pause(boolean replay) {
        if (mediaPlayer == null) {
            return;
        }

        mediaPlayer.pause();
        isPlay = false;
        isReplay = replay;
//        if (replay) {
//            //不设置暂停状态
//            isPause = false;
//        } else {
        isPause = true;
//        }

    }

    @Override
    public int getDuration() {
        if (isPrepare) {
            return mediaPlayer.getDuration();
        }

        return 0;
    }

    @Override
    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    @Override
    public void seekTo(int pos) {
        mediaPlayer.seekTo(pos);
        if (myController != null) {
            myController.onProgress(pos);
        }
    }

    @Override
    public boolean isPlaying() {

        if (TextUtils.isEmpty(currentPath)) {
            return false;
        }

        if (isPlay) {
            return true;
        }

        return mediaPlayer.isPlaying();
    }

    @Override
    public int getBufferPercentage() {
        return 0;
    }

    @Override
    public boolean canPause() {
        return true;
    }

    @Override
    public boolean canSeekBackward() {
        return false;
    }

    @Override
    public boolean canSeekForward() {
        return false;
    }

    @Override
    public int getAudioSessionId() {
        return getDuration();
    }

    public interface MyController {
        void onProgress(int progress);
    }

    public interface MyPlayFinishListener {
        void onfinish(String audioId);
    }

    public interface MyErrorListener {
        void onError(String msg);
    }


    public String getCurrentPath() {
        return currentPath;
    }

    public int getCurrentProgress() {
        return currentProgress;
    }


    public void setErrorListener(MyErrorListener errorListener) {
        this.errorListener = errorListener;
    }

    public void setFinishListener(MyPlayFinishListener finishListener) {
        this.finishListener = finishListener;
    }

    public MyMediaPlayer setMyController(MyController myController) {
        this.myController = myController;
        return this;
    }

    public void removeController() {
        myController = null;
    }


}
